#!/usr/bin/env python
# encoding: utf-8
# @author: Lin Han
# @contact: voldemort22@126.com
# @file: migrate_clamp_database.py
# @time: 2021/3/30 19:20
# @desc:
import json
import os
from itertools import islice

import oss2
import requests
import pymongo

from .utils.md5_tools import getFileMd5
from .utils.oss.oss import bucket, download_file_from_oss
from .utils.utils import read_json

from .views.configs import *


clamp_local_address = r"D:\project\do_design_fastapi_backend\data\DataLibrary\DataLibrary\Clamp"

original_clamp = read_json(r"D:\workspace\data_platform\script\original_clamp.json")

oss_file_dirname = "DODesign_Dev/DataLibrary"

new_clamp_list = []

for index, value in enumerate(original_clamp):
    if "_id" in value.keys():
        value.pop("_id")
    temp_dict = {}
    temp_dict["number"] = value["number"]
    temp_dict["time"] = value["time"]
    temp_dict["Name"] = value["Name"]
    temp_dict["desc"] = "Copied from original database"
    temp_dict["type"] = "1"
    temp_dict["Version"] = "1.0"
    temp_dict["isFeature"] = value["isFeature"]
    temp_dict["isFlag"] = value["isFlag"]
    temp_dict["tag"] = value["tag"]
    # Standard change to list from string
    temp_dict["tag"]["standard"] = [temp_dict["tag"]["standard"]]

    # 到这个地址去查一下，如果有文件（理论上应该只有一个文件），返回这个文件的地址
    clamp_folder_path = f"{oss_file_dirname}/Clamp/{value['CGuid']}"
    for obj in oss2.ObjectIteratorV2(bucket, prefix=clamp_folder_path):
        # TODO: 下载下来计算一下md5值
        if obj.key.endswith(".CATPart"):
            temp_dict["CatPartAddress"] = obj.key
            catia_file_path = f"D:/workspace/data_platform/temp_data/{temp_dict['Number']}/{temp_dict['Name']}"
            download_file_from_oss(obj.key, local_file_name=catia_file_path)
            temp_dict["CatPartMD5"] = getFileMd5(catia_file_path)

        if obj.key.endswith(".stp"):
            temp_dict["StpAddress"] = obj.key
            stp_file_path = f"D:/workspace/data_platform/temp_data/{temp_dict['Number']}/{temp_dict['Name'].replace('CATPart', 'stp')}"
            download_file_from_oss(obj.key, local_file_name=stp_file_path)
            temp_dict["StpMD5"] = getFileMd5(stp_file_path)

    workpiece_folder_path = f"{oss_file_dirname}/Work/{value['CWork']}"
    for obj in oss2.ObjectIteratorV2(bucket, prefix=workpiece_folder_path):
        if obj.key.endswith("Work.stl"):
            temp_dict["WorkPieceStlAddress"] = obj.key
            workpiece_catia_file_path = f"D:/workspace/data_platform/temp_data/{temp_dict['Number']}/Work.stl"
            download_file_from_oss(obj.key, local_file_name=workpiece_catia_file_path)
            temp_dict["WorkPieceStlMD5"] = getFileMd5(workpiece_catia_file_path)

    print(index)
    print(temp_dict)

    new_clamp_list.append(temp_dict)


myclient = pymongo.MongoClient(MONGO_URL)
mydb = myclient["do_center"]
clamp = mydb["history_clamp"]
clamp.insert_many(new_clamp_list)





























